<template>
	<div>
		<Banner :banners="banners"></Banner>
		<!-- <div class="clear" id="time_container">
			<p class="fl p28 black">距离本场结束：<span>{{countdownTime}}</span></p>
			<router-link to="/goods/more" class="fr c-btn highlight">下期预告</router-link>
		</div> -->
            

		<div v-if="contentLoaded">
			<Item v-for="(item, i) in list" :key="i" v-show="!expired"
				:item="item"></Item>
			<div class="normal-tip" v-if="!list.length"
				style="marginTop: 3.5rem">暂无可秒杀商品</div>
		</div>
	</div>
</template>
<script>
import Banner from './Banner'
import Item from '@/components/Item'
import { mapGetters, mapActions } from 'vuex'
import { Indicator } from 'mint-ui'
export default {
	name: 'Homepage',
	async created(){
		this.$store.dispatch('getBanners')
		await this.getGoods()
		this.contentLoaded = true
    },
    mounted(){
        // console.log(this)
        // console.log(this.$data)
    },
	data(){
		return {
			contentLoaded: false,
			countdownFn: '',
			countdownTime: '00:00:00',
			expired: false
		}
	},
	computed: mapGetters({
	   banners: 'banners',
	   list: 'goods/limitedGoodsList',
	   endTime: 'goods/limitedGoodsEnd',
	 }),
	methods:{
		async getGoods(){
			Indicator.open()
			this.expired = true
			await this.$store.dispatch('goods/getLimitedGoods')
			// 避免拉取时已过期的特殊情况
			if (isNaN(this.endTime) || this.endTime*1000 - Date.now() <= 0) {
				this.countdownTime = '已结束'
			} else {
				this.expired = false
				this.countdown()
				this.countdownFn = setInterval(this.countdown, 1000)
			}
			Indicator.close()
		},
		countdown(){
			const t = this.endTime*1000 - Date.now()
			const seconds = Math.floor( (t/1000) % 60 )
			const minutes = Math.floor( (t/1000/60) % 60 )
			const hours = Math.floor( t/(1000*60*60) )
			const add0 = (num) => num < 10 ? `0${num}` : num
			this.countdownTime = `${add0(hours)}:${add0(minutes)}:${add0(seconds)}`
			if(t <= 0) {
				clearInterval(this.countdownFn)
				// 过期则再次刷新列表
				this.getGoods()
			}
		}
	},
	beforeDestroy(){
		clearInterval(this.countdownFn)
	},
	components:{Banner, Item}
}
</script>
<style lang='less' scoped>
.swiper-slide{
	width: 4.93rem;
	display: inline-block;
}
#time_container{
	padding: 0 .3rem;
    background: #fff;
    height: .9rem;
	line-height: 0.9rem;
	border-bottom: 1.5px solid #ddd;
	.c-btn{
		margin-top: .1rem;
	}
}
</style>
